#include "RenderTarget.h"
#include "../Utility/Renderer/TextureManager.h"

RenderTarget::RenderTarget()
{
    m_pTexture = 0;
    m_pOldRT = 0;
    m_TargetIndex = -1;
	m_pSurface = 0;
}

RenderTarget::~RenderTarget()
{
	if(m_pSurface)
	{
		m_pSurface->Release();
		m_pSurface = 0;
	}
	if(m_pTexture != 0)
	{
		m_pTexture->Release();
		m_pTexture = 0;
	}	
}

bool RenderTarget::Create(UINT _width, UINT _height, D3DFORMAT _format)
{
	if(TextureManager::CreateTexture(_width, _height, 0, D3DUSAGE_RENDERTARGET, _format, D3DPOOL_DEFAULT, m_pTexture, 0))
	{
		(m_pTexture)->GetSurfaceLevel(0,&m_pSurface);
		return true;
	}

	return false;
}

void RenderTarget::ActivateTarget(DWORD targetIndex)
{
	m_TargetIndex = targetIndex;

	D3D9Renderer::device->GetRenderTarget(targetIndex,&m_pOldRT);
	D3D9Renderer::device->SetRenderTarget(targetIndex,m_pSurface);
}

void RenderTarget::RevertTarget()
{
	D3D9Renderer::device->SetRenderTarget(m_TargetIndex,m_pOldRT);

	if(m_pOldRT)
		m_pOldRT->Release();

	m_TargetIndex = -1;
}

IDirect3DTexture9* RenderTarget::GetTexture() 
{ 
	return m_pTexture; 
}